/******************************************************************
 * Copyright @ 2023 广州牛师帮科技文化有限公司. All rights reserverd.
 * @file   src\component\ErrorViewer\index.tsx
 * @author 朱剑豪
 * @date   2023/10/11 14:41
 * @desc   错误查看器
 *    在开发环境下，当存在异常时，使用这个显示异常信息
 ******************************************************************/

import WarningOutlined from "@ant-design/icons/lib/icons/WarningOutlined"
import { LiveStorage } from "@nsb/common-tools/dist/LiveStorage"
import { useArrStorage } from "@nsb/common-tools/dist/hooks/useArrayStorage"
import { FloatButton, Input, Modal, Tabs, TabsProps } from "antd"
import dayjs from 'dayjs'
import { useState } from "react"
import styles from './index.module.scss'
const storageType = 'session';
const storageKey = 'server_error_list';

export namespace ErrorViewer {

  export function addError(str: string) {
    if (__ENV__ === 'release')
      return;
    const storage = LiveStorage.get(storageType)
    const raw = storage.getItem(storageKey);
    let list: string[] = []
    if (raw) {
      list = JSON.parse(raw) || []
    }
    list.push('' + Date.now() + ';' + str);
    storage.setItem(storageKey, JSON.stringify(list))
  }

  export function Component() {
    const [isOpen, setIsOpen] = useState(false)
    const close = () => setIsOpen(false)
    const open = () => setIsOpen(true)
    const [list_, setList] = useArrStorage<string>(storageType, storageKey)
    const list = list_ || []

    if (__ENV__ === 'release')
      return null;

    const removeError = (idx: number) => {
      list.splice(idx, 1)
      setList([...list])
      list.length || close();
    }
    const clear = () => {
      setList([])
      close()
    }
    const onTabEdit: TabsProps['onEdit'] = (key, action) => {
      typeof key === 'string' && action === 'remove' && removeError(Number(key))
    }
    const hasError = !!list?.length
    const tabs: TabsProps["items"] = list?.map((v, i) => {
      const idx = v.indexOf(';')
      const key = v.substring(0, idx);
      const text = v.substring(idx + 1);
      return {
        key: i.toString(),
        label: dayjs(Number(key)).format('YYYY-MM-DD HH:mm:ss.SSS'),
        closable: true,
        onClose: () => removeError(i),
        children: <Input.TextArea className={styles.text_area} value={text} />
      }
    })
    return <>
      <FloatButton
        icon={<WarningOutlined />}
        type="primary"
        onClick={open}
        style={hasError ? undefined : { display: 'none' }} />
      <Modal
        title={null}
        open={hasError && isOpen}
        onCancel={close}
        okText='clear'
        onOk={clear}
        cancelText='cancel'
        closable={false}
        wrapClassName={styles.modal_wrap}
        className={styles.modal}>
        <Tabs
          size='small'
          items={tabs}
          type="editable-card"
          hideAdd
          onEdit={onTabEdit} />
      </Modal>
    </>
  }
}
